package com.lancoo.cvas.arrangecourse.common;

import cn.hutool.core.util.ObjUtil;
import com.lancoo.cvas.arrangecourse.entities.ClassHour;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Description 通用工具类
 * @Author Fortysun
 * @Date 2023/8/25 9:27
 **/
public class ClassHourUtil {

    /**
     * 获取课表map的元素大小
     * @param classHourMap
     * @return
     */
    public static Integer getMapElementSize(ConcurrentHashMap<String, CopyOnWriteArrayList<ClassHour>> classHourMap) {
        Integer count = 0;
        if (classHourMap != null && !classHourMap.isEmpty()) {
            for (ConcurrentHashMap.Entry<String, CopyOnWriteArrayList<ClassHour>> entry : classHourMap.entrySet()) {
                count += entry.getValue().size();
            }
        }

        return count;
    }

    /**
     * 将课表list，转换成map，key为课时编码，0101代表周一第1节
     * @param lockedClassHourList 锁定的课表信息
     * @return
     */
    public static ConcurrentHashMap<String, CopyOnWriteArrayList<ClassHour>> getClassHourMap(
            CopyOnWriteArrayList<ClassHour> lockedClassHourList) {
        //将列表，按照timeslotCode，进行分组，即作为key，生成map
        ConcurrentHashMap<String, CopyOnWriteArrayList<ClassHour>> classHourMap = null;
        if (lockedClassHourList != null && !lockedClassHourList.isEmpty()) {
            // CopyOnWriteArrayList<ClassHour>转换为 ConcurrentHashMap<String, CopyOnWriteArrayList<ClassHour>>
            classHourMap = lockedClassHourList.stream()
                    .filter(classHour -> ObjUtil.isNotNull(classHour.getTimeslotRoom()) && ObjUtil.isNotNull(classHour.getTimeslotRoom().getTimeslotCode()))//过滤掉未分配教室课时分组的课表数据
                    .collect(Collectors.groupingBy(
                            classHour -> classHour.getTimeslotRoom().getTimeslotCode(),
                            () -> new ConcurrentHashMap<>(),
                            Collectors.toCollection(CopyOnWriteArrayList::new)
                    ));
        } else {
            //如果没有锁定的课程，new一个map出来进行返回，防止发生空指针异常
            classHourMap = new ConcurrentHashMap<>();
        }

        return classHourMap;
    }
}